package com.cskaoyan.controller.profile;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.po.adminpo.MarketAdmin;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.util.common.DateUtils;
import com.cskaoyan.util.crypt.CryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * @Author: zhang tao
 * @Description:
 * @Date: 2022/7/15 16:56
 */
@RestController
@RequestMapping("admin/profile")
public class ProfileController {

    @Autowired
    MarketAdminMapper mapper;

    @PostMapping("password")
    public BaseRespVo changePassword(@RequestBody Map map, HttpSession session) {

        String newPassword=(String)map.get("newPassword");
        String newPassword2=(String)map.get("newPassword2");
        String oldPassword=(String)map.get("oldPassword");
        // String newPassword = CryptUtils.encryptStr((String) map.get("newPassword"));
        // String newPassword2 = CryptUtils.encryptStr((String) map.get("newPassword2"));
        // String oldPassword = CryptUtils.encryptStr((String) map.get("oldPassword"));

        if (newPassword == null) {
            return BaseRespVo.invalidParameter("不能输入空密码");
        }
        if (newPassword.length() < 6) {
            return BaseRespVo.invalidParameter("密码至少要六位");
        }
        if (!newPassword.equals(newPassword2)) {
            return BaseRespVo.invalidParameter("两次密码不一致");
        }
        if (newPassword.equals(oldPassword)) {
            return BaseRespVo.invalidParameter("不允许修改同样的密码");
        }
        MarketAdmin po = (MarketAdmin) session.getAttribute("principal");
        if (!po.getPassword().equals(oldPassword)) {
            return BaseRespVo.invalidParameter("原密码错误");
        }
        MarketAdmin marketAdmin = new MarketAdmin();

        // String cryptPassword = CryptUtils.encryptStr(newPassword);
        // marketAdmin.setPassword(cryptPassword);
        marketAdmin.setPassword(newPassword);

        marketAdmin.setUpdateTime(DateUtils.time());
        marketAdmin.setId(po.getId());
        try {
            mapper.updateByPrimaryKeySelective(marketAdmin);
            po.setPassword(newPassword);
            session.setAttribute("principal", po);
            return BaseRespVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseRespVo.invalidParameter("系统更新，请稍后");
    }
}
